import {parseArgs} from 'node:util'
import {readdirSync,statSync,existsSync} from 'node:fs'
import { dirname,resolve} from 'node:path'
import { fileURLToPath } from 'node:url'
import inquirer from 'inquirer'
// import { NODE_ENV_ENUM } from './util.js'
import {build} from 'esbuild'

/**
 * 包信息，构建选项，解析和创建
 */
const __dirname = dirname(fileURLToPath(import.meta.url))
const packagesDir = resolve(__dirname,'../packages')
const packages = readdirSync(packagesDir).filter(packageName => {
  return statSync(`${packagesDir}/${packageName}`).isDirectory() &&
         existsSync(`${packagesDir}/${packageName}/package.json`)
})


/**
 * 命令行参数准备
 */
const {values} = parseArgs({
  options:{
    question:{
      type:'boolean',
      short:'q',
      default:false
    },
    watch:{
      type:"boolean",
      short:'w',
      default:false
    },
    target:{
      type:'string',
      short:"t"
    },
  }
})
const {watch,target,question} = values
// const env = devMode 
//   ? NODE_ENV_ENUM.development
//   : NODE_ENV_ENUM.production
// const fileNameSplite = devMode ? 'dev':'prod'

main()
async function main(){
  if(question){
    const targetPackage = await askTargetPackage()
    return buildTarget(targetPackage)
  }
  if(!target){
    if(watch){
      const targetPackage = await askTargetPackage()
      return buildTarget(targetPackage,true)
    }else {
      return buildAll()
    }
  }
  if(!packages.includes(target)){
    throw new Error('不存在这个包')
  }
  buildTarget(target,watch)
}

async function askTargetPackage(){
  const question = [
    {
      type: 'list',
      message: 'select a package to dev',
      name: 'target',
      choices:[...packages]
    }
  ]
  const answer =  await inquirer.prompt(question)
  return answer.target
}

async function buildTarget(target,isWatch = false){
  const ctx = build({
    entryPoints:[resolve(packagesDir,target,'src/index.ts')],
    bundle:true,
    outfile:resolve(packagesDir,target,`dist/${target}.esm-bundler.js`),
    format:'esm',
    sourcemap: true,
    tsconfig:'tsconfig.json',
    define:{
      __DEV__:'true'
    }
  })
  if(isWatch){
    ctx.watch()
  }
}

async function buildAll(){
  //todo: 开启子进程同时并行运行build target
  const task = []
  packages.forEach(item => task.push(buildTarget(item)))
  try{
    await Promise.all(task)
  }catch(e){
    console.log(e.message)
  }finally{
    console.log('build over')
  }
}


